#ifndef _GATEWAY_CLIENT_H_
#define _GATEWAY_CLIENT_H_

#include "gateway_task.h"
#include "gateway_network_event.h"
#include "../mqttservice/mqttservice.h"
//#include <string>
#include <boost/enable_shared_from_this.hpp>
#include "gateway_protocol.h"

typedef enum{CMDCONNECT = 0, CMDSTATE, CMDPING, CMDEND}CMDTYPE;
typedef enum{PULISH = 0, SUBSCRIBE, ONCONNECT}TASKTYPE;
typedef struct{
	std::string strcmddata;
	CMDTYPE cmdtype;
}CMDDATA;

class gateway_client : public gateway_stream_event, public IMqttEvent, public gateway_task,  public boost::enable_shared_from_this<gateway_task> {
	struct onmessage_data
	{
		std::string strid;
		ShadowActions actions;
		std::string payload;
	};
	struct pulish_data
	{
		char * data;
		int datalen;
		//std::string strjson;
	};
	struct event_data{
		TASKTYPE tasktype;
		void *data;
	};
	
public:
	explicit gateway_client(gateway_stream_ptr stream_ptr);
	virtual ~gateway_client();

	/**** gateway_stream_event ****/

	//网络连接事件
	virtual int stream_init();

	//网络断开事件
	virtual int stream_clean();

	//网络读取事件
	virtual int stream_read(unsigned char* data, unsigned int dataLen);

	/**** gateway_task ****/
	virtual int on_task(void* param);

public:
    
	int OnConnect(CMQTTService *mq, std::string strid, int rc);
	int OnDisconnect(CMQTTService *mq, std::string strid, int rc);
	int OnMessage(CMQTTService *mq, std::string strid, ShadowActions actions, std::string payload);
	int OnSubscribe(CMQTTService *mq, std::string strid, int mid, int qos_count, const int *granted_qos);
    int OnUnsubscribe(CMQTTService *mq, std::string strid, int mid);
	int OnPublish(CMQTTService *mq, std::string strid, int mid);

public:
	void close();	
	std::string get_addr(){return _addr;}
private:

	int handle_parse_packet(unsigned char* buf, unsigned int bufLen, unsigned int &used);

	int handle_mqtt_event(std::string strjson);

	int get_mqtt_config(MQTTCONFIG & mqttconfig);

	int gateway_packet_ack();

	int task_pulish(std::string strpulishdata);

	void task_onmessage(std::string strid, ShadowActions actions, std::string strpayload);

	std::string get_json_val(const std::string strJson, const std::string strkey);
	
	int deal_update(const std::string strJson);

	int deal_get(const std::string strdevid, const std::string strJson);

	int deal_ctrl(const std::string strdevid, const std::string strJson);
	
	int send_cmd(std::string strcmd);

	int get_current_stamp();
	//boost::shared_ptr<gateway_client> get_ptr();

private:		
	std::string _host;
	bool _is_connected;
	unsigned short _port;
	std::string _addr;//ip:port
	//unsigned int _last_packet_id;
	unsigned int _ping_time;
	std::string _strdevid;
	std::string strkey;
	MQTTCONFIG _mqttconfig;
	gateway_stream_ptr _stream_ptr;
	//cmqtt_service_ptr _mqtt_ptr;
	CMQTTService *_mqtt;
	gateway_protocol _protocol;
	boost::shared_ptr<gateway_client> _client_ptr;
};

typedef boost::shared_ptr<gateway_client>gateway_client_ptr;
#endif 